<template>
  <el-card class="box-card">
    <!-- 面包屑导航 -->
    <div slot="header" class="clearfix">
      <breadcrum>素材管理</breadcrum>
    </div>
    <!-- 素材管理顶部 -->
    <div style="margin-bottom: 20px">
      <el-radio-group v-model="collected" size = 'mini' @change="hcollected(image)">
        <el-radio-button label="全部" ></el-radio-button>
        <el-radio-button label="收藏" ></el-radio-button>
      </el-radio-group>
      <el-button size = 'mini' type="success" style="float: right" @click="showDialog">上传素材<i class="el-icon-upload el-icon--right"></i></el-button>
    </div>
    <!-- 图片列表 -->
    <el-row :gutter="10">
      <el-col :span="4" class="img_item" v-for="image in images" :key='image.id'>
          <el-image
            style="height:180px;width:180px"
            :src="image.url"
            fit="cover"></el-image>
          <div class="option" v-show="collected === '全部'">
            <!-- 依据获取的结果，给image.is_collected为true的那个添加类名 -->
            <span class="el-icon-star-off" :class="{red: image.is_collected}" @click="toggleCollect(image)"></span>
            <span class="el-icon-delete" ></span>
          </div>
      </el-col>
    </el-row>
    <!-- 分页区 -->
    <el-pagination
      @current-change='pageChange'
      style="margin-top:10px"
      background
      layout="prev, pager, next"
      :total="total_count">
    </el-pagination>
    <!-- 弹出框 -->
    <el-dialog
      :append-to-body = 'true'
      title="上传素材"
      :visible.sync="dialogVisible">
      <!-- 弹窗内部内容区 -->
      <el-upload
        class="avatar-uploader"
        action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
        :headers= headers
        name = 'image'
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-image v-if="imageUrl" :src="imageUrl" @load="slowLoad" class="avatar"/>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>
</el-card>
</template>

<script>
export default {
  name: 'images',
  data () {
    return {
      collected: '全部',
      images: [],
      page: 1,
      total_count: 0,
      dialogVisible: false,
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    }
  },
  methods: {
    // 加载图片
    async loadImage () {
      const params = this.buildParams()
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images',
          method: 'get',
          params
        })
        console.log('获取图片成功', res)
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count
      } catch (err) {
        console.log(err)
      }
    },
    // 构造查询参数
    buildParams () {
      const params = {
        collect: this.collected === '收藏',
        page: this.page,
        per_page: 20
      }
      return params
    },
    // 用户点击全部和收藏的反应
    hcollected () {
      this.page = 1
      this.loadImage()
    },
    // 分页加载
    pageChange (currentPage) {
      console.log('当前是第', currentPage)
      this.page = currentPage
      // 依据当前页面。发送请求获取数据
      this.loadImage()
    },
    // 点击弹出上传图片框
    showDialog () {
      this.dialogVisible = true
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data.url
      console.log('上传图片成功', res)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 图片上传延迟效果
    slowLoad () {
      setTimeout(() => {
        this.dialogVisible = false
        this.loadImage()
        this.imageUrl = ''
      }, 1000)
    },
    // 用户点击收藏图标
    async toggleCollect (image) {
      // 确认此时的参数指代
      console.log('点击收藏图标', image)
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images/' + image.id,
          method: 'put',
          data: {
            collect: !image.is_collected
          }
        })
        console.log(res)
      } catch (err) {
        console.log(err)
      }
      image.is_collected = !image.is_collected
    }
  },
  // 生命周期函数，进入页面就加载图片
  created () {
    this.loadImage()
  }
}
</script>

<style lang="less" scoped>
  .img_item {
    position: relative;
    box-sizing: border-box;
  }
  .option {
    position: absolute;
    left: 5px;
    width:180px;
    bottom: 5px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
  }
  .red {
    color: red
  }
  .avatar-uploader {
    text-align: center;
  }
  .avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
